<%@page import="java.text.SimpleDateFormat"%>
<%@ page import="com.pension.model.dto.BoardComment"%>
<%@ page import="com.pension.model.dto.Member"%>
<%@ page import="com.pension.model.dto.Board"%>
<%@page import="java.util.Date"%>
<%@ page import="java.sql.Timestamp"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" session="true"%>

<%!
String isCommentEditable(Member member, String writer) {	
	
	//Member member = (Member)session.getAttribute("loginuser");
	if (member == null) return "none";
	
	//admin, user권한 전체 글쓰기, 수정
	if (member.getMemberId().equals(writer) ||
		member.getUserType().equals("admin")) {
		return "block";
	}
	else {
		return "none";
	}
}
%>
<!DOCTYPE html>

<html>
<head>

	<meta charset="utf-8" />
	<title>글쓰기</title>
	<link rel="Stylesheet" href="/pension/styles/board/default.css" />
	<link rel="Stylesheet" href="/pension/styles/board/input2.css" />
	<script type="text/javascript">
	function doDelete(boardno) {
		var ok = confirm("게시물을 삭제 합니다.");
		if (ok) {
			//삭제 처리
			location.href="delete.action?boardno=" + boardno;
		}
	}
	
	function deleteComment(commentNo, boardNo, pageNo) {
		if (confirm(commentNo + "번 댓글을 삭제할까요?")) {
			location.href='deletecomment.action?commentno=' 
				+ commentNo + "&boardno=" + boardNo + "&pageno=" + pageNo;
		}
	}
	
	function toggleCommentStatus(commentNo, edit) {		
		document.getElementById('commentview' + commentNo).style.display = edit ? 'none' : 'block';
		document.getElementById('commentedit' + commentNo).style.display = edit ? 'block' : 'none';
	}
	</script>
</head>
<body>

	<div id="pageContainer">
		<% Date date = new Date(); %>
		<% pageContext.include("/WEB-INF/views/include/header.jsp"); %>
		
		<div style="padding-top:25px;text-align:center">
		<div id="inputcontent">
		    <div id="inputmain">
		        <div class="inputsubtitle">게시판 글 내용</div>
		        <% Board board = (Board)request.getAttribute("board"); %>
		        <table>
		            <tr>
		                <th>제목</th>
		                <td><%= board.getTitle() %></td>
		            </tr>
		            <tr>
		                <th>작성자</th>
		                <td><%= board.getWriter() %></td>
		            </tr>
		            <tr>
		                <th>작성일</th>
		                <td><%= board.getRegDate() %></td>
		            </tr>
					<tr>
		                <th>조회수</th>
		                <td><%= board.getReadCount() %></td>
		            </tr>
		            <tr>
		                <th>내용</th>
		                <td style="height:200px;vertical-align:top">		                    
		                    <%= board.getContent().replace("\r\n", "<br />") %>
		                </td>
		            </tr>
		        </table>
		        <div class="buttons">
		        	<%
		        		String pageNo = request.getParameter("pageno");
		        		if (pageNo == null || pageNo.length() == 0)
		        			pageNo = "1";
		        	%>
		        	<% Member member = (Member)session.getAttribute("loginuser"); %>
		        	<% if (member.getMemberId().equals(board.getWriter()) || member.getUserType().equals("admin")) { %>   <!-- 관리자 권한 포함 -->
		        	[&nbsp;<a href="editform.action?boardno=<%= board.getBoardNo() %>&pageno=<%= pageNo %>">편집</a>&nbsp;]
		        	[&nbsp;<a href="javascript:doDelete(<%= board.getBoardNo() %>);">삭제</a>&nbsp;]
		        	<% } %>
		        	[&nbsp;<a href="replyform.action?boardno=<%= board.getBoardNo() %>&pageno=<%= pageNo %>">댓글쓰기</a>&nbsp;]
		        	[&nbsp;<a href='list.action?pageno=<%= pageNo %>'>목록보기</a>&nbsp;]
		        </div>
		    </div>
		</div>
		
		<!-- comment 쓰기 영역 -->
		<br /><br />
		
		<%-- 로그인 한 사용자만 댓글을 쓸 수 있습니다. --%>
		<% if (session.getAttribute("loginuser") != null) { %>
		<form id="commentform" 
			action="writecomment.action" method="post">
			<input type="hidden" name="boardno"
				value="<%= board.getBoardNo() %>" />
			<input type="hidden" name="pageno"
				value="<%= pageNo %>" />
			<table style="width:600px;border:solid 1px;margin:0 auto">
	            <tr>
	                <td style="width:550px">
	                	
	                    <textarea name="content" 
	                    	style="width:550px" rows="3"></textarea>
	                    
	                </td>
	                <td style="width:50px;vertical-align:middle">
	                	<a href="javascript:document.getElementById('commentform').submit();"
	                		style="text-decoration:none; color:#B3B3B3;">
	                		댓글<br />등록
	                	</a>
	                </td>
	            </tr>                    
	        </table>
        </form>
        <% } %>
        
                <hr align="center" style="width:600px;" />
        <% 	int bcCount=0; %>
        <% if (board.getComments().size() == 0) { %>
        <h3 id="nodata" style="text-align:center; font-size: 15px; color: #DBDBDB; font-family: 굴림;">
            작성된 댓글이 없습니다.
        </h3>
        <% } else { %>        
		<!-- comment 표시 영역 -->
		<table style="width:600px;border:solid 1px;margin:0 auto">
		<% for(BoardComment bcomment : board.getComments()) { %>
        	<tr>
        		<td style="text-align:left;margin:5px;border-bottom: solid 1px; color: #ffffff;">
        		<div id='commentview<%= bcomment.getCommentNo() %>'>
                    <%= bcomment.getWriter() %> &nbsp;&nbsp;
					<%
					SimpleDateFormat dfhm = new SimpleDateFormat(
							"yyyyMMddHHmmss"); //날짜와 시간까지 계산해본다.
					SimpleDateFormat dfhm2 = new SimpleDateFormat(
							"yyyy-MM-dd");

					String resdate = dfhm.format(bcomment.getRegDate());
					String today = dfhm.format(date.getTime());
					String orgtime = dfhm2.format(bcomment.getRegDate());

					Date beginDate = null;
					Date endDate = null;

					long diff = 0;
					long diffDays = 0;

					String timename = "";

					long diffTimes = 0;

					//parse: 문자형 날짜 -> Date 형태로 변환
					beginDate = dfhm.parse(resdate);
					endDate = dfhm.parse(today);

					//System.out.println(resdate);
					//System.out.println(today);
					//System.out.println(s_snsupload.getS_regdate());
					//System.out.println(endDate.getTime());
					//System.out.println(beginDate.getTime());

					diff = endDate.getTime() - beginDate.getTime(); // 0.001초 단위로 계산됨

					//diffDays  = diff / (24 * 60 * 60 * 1000);

					//System.out.println(diff);

  					if (diff < 60000) {
						diffTimes = diff / 1000;
						timename = "방금 전";
						out.print("["+bcomment.getRegDate()+"]  "+timename);
					}
  					else if (diff < (60 * 60 * 1000)) {
						diffTimes = diff / (60 * 1000);
						timename = "분 전";
						out.print("["+bcomment.getRegDate()+"]  "+diffTimes + timename);
					} else if (diff < (24 * 60 * 60 * 1000)) {
						diffTimes = diff / (60 * 60 * 1000);
						timename = "시간 전";
						out.print("["+bcomment.getRegDate()+"]  "+diffTimes + timename);
					} else if (diff >= (24 * 60 * 60 * 1000)){
						 diffTimes = diff / (24 * 60 * 60 * 1000);
						 timename = "일 전";
						 out.print("["+bcomment.getRegDate()+"]  "+diffTimes + timename);
					} /* else if (diff >= (24 * 60 * 60 * 1000)){
					 diffTimes = diff / (24 * 60 * 60 * 1000);
					 timename = "일 전";
					 out.print(diffTimes + timename);
					} */
					%>
					
                    <%-- [ <%= bcomment.getRegDate() %> ] --%>

                    <br /><br />
                    <span>
                        <%= bcomment.getContent().replace("\r\n", "<br />") %>
                    </span>
                    <br /><br />
                    <div style="display: <%= isCommentEditable((Member)session.getAttribute("loginuser"), bcomment.getWriter()) %>">
                    	<a href="javascript:toggleCommentStatus(<%= bcomment.getCommentNo() %>, true);" 
                    		style="text-decoration:none; color:#A1A1A1;font-weight: bold;font-size: 13px;">편집</a>
                    	&nbsp;
                    	<a href="javascript:deleteComment(<%= bcomment.getCommentNo() %>, <%= board.getBoardNo() %>, <%= pageNo %>)"
                    		style="text-decoration:none; color:#A1A1A1;font-weight: bold;font-size: 13px;">삭제</a>
                    </div>
                </div>
                
                <div id='commentedit<%= bcomment.getCommentNo() %>' style="display: none">
					
					<br /><br />
					<form id="commenteditform<%= bcomment.getCommentNo() %>" 
						action="updatecomment.action" method="post">
					<input type="hidden" name="boardno"
						value="<%= board.getBoardNo() %>" />
					<input type="hidden" name="pageno"
						value="<%= pageNo %>" />
					<input type="hidden" name="commentno"
						value="<%= bcomment.getCommentNo() %>" />
					<textarea name="content" style="width: 600px" rows="3" 
						maxlength="200"><%= bcomment.getContent() %></textarea>
					</form>
					<br />
					<div>
						<a href="javascript:document.getElementById('commenteditform<%= bcomment.getCommentNo() %>').submit();"
							style="text-decoration:none; color:#A1A1A1;font-weight: bold;font-size: 13px;">수정</a> 
						&nbsp; 
						<a href="javascript:toggleCommentStatus(<%= bcomment.getCommentNo() %>, false);"
							style="text-decoration:none; color:#A1A1A1;font-weight: bold;font-size: 13px;">취소</a>
					</div>
				</div>
	
				</td>
        	</tr>
        <% } %>
        </table>		
		<% } %>
        <br /><br /><br /><br /><br /><br />
	
	</div>
	</div>

</body>
</html>